/**
 * @Description: 模拟API服务 - 替代json-server的纯前端数据模拟
 * @Author: lujq
 * @Date: 2025-01-04
 * @LastEditors: lujq
 * @LastEditTime: 2025-01-04 18:00:00
 */

import type { ApiResponse } from '@/types'

// 模拟数据存储
class MockDataStore {
  private data: Record<string, any[]> = {}
  private initialized = false

  constructor() {
    this.initData()
  }

  /**
   * 初始化模拟数据
   */
  private async initData() {
    if (this.initialized) return

    // 从db.json文件加载数据（实际项目中可以直接在这里定义数据）
    try {
      const response = await fetch('/db.json')
      const jsonData = await response.json()
      this.data = jsonData
      this.initialized = true
    } catch (error) {
      console.warn('无法加载db.json，使用默认数据', error)
      this.initDefaultData()
    }
  }

  /**
   * 初始化默认数据
   */
  private initDefaultData() {
    this.data = {
      customers: [],
      orders: [],
      products: []
    }
    this.initialized = true
  }

  /**
   * 获取数据
   */
  async getData(resource: string): Promise<any[]> {
    await this.initData()
    return this.data[resource] || []
  }

  /**
   * 获取单个数据项
   */
  async getDataById(resource: string, id: string): Promise<any | null> {
    const data = await this.getData(resource)
    return data.find(item => item.id === id) || null
  }

  /**
   * 添加数据
   */
  async addData(resource: string, item: any): Promise<any> {
    await this.initData()
    if (!this.data[resource]) {
      this.data[resource] = []
    }
    
    // 生成新ID
    const maxId = this.data[resource].reduce((max, current) => {
      const currentId = parseInt(current.id) || 0
      return currentId > max ? currentId : max
    }, 0)
    
    const newItem = {
      ...item,
      id: String(maxId + 1),
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }
    
    this.data[resource].push(newItem)
    return newItem
  }

  /**
   * 更新数据
   */
  async updateData(resource: string, id: string, updates: any): Promise<any | null> {
    await this.initData()
    const data = this.data[resource] || []
    const index = data.findIndex(item => item.id === id)
    
    if (index === -1) return null
    
    const updatedItem = {
      ...data[index],
      ...updates,
      updateTime: new Date().toISOString()
    }
    
    this.data[resource][index] = updatedItem
    return updatedItem
  }

  /**
   * 删除数据
   */
  async deleteData(resource: string, id: string): Promise<boolean> {
    await this.initData()
    const data = this.data[resource] || []
    const index = data.findIndex(item => item.id === id)
    
    if (index === -1) return false
    
    this.data[resource].splice(index, 1)
    return true
  }

  /**
   * 批量删除数据
   */
  async batchDeleteData(resource: string, ids: string[]): Promise<number> {
    await this.initData()
    let deletedCount = 0
    
    for (const id of ids) {
      const success = await this.deleteData(resource, id)
      if (success) deletedCount++
    }
    
    return deletedCount
  }
}

// 创建全局数据存储实例
const mockStore = new MockDataStore()

/**
 * 模拟API延迟
 */
const delay = (ms: number = 300) => new Promise(resolve => setTimeout(resolve, ms))

/**
 * 模拟分页处理
 */
function paginateData<T>(data: T[], page: number = 1, pageSize: number = 10) {
  const total = data.length
  const totalPages = Math.ceil(total / pageSize)
  const start = (page - 1) * pageSize
  const end = start + pageSize
  const items = data.slice(start, end)
  
  return {
    items,
    total,
    page,
    pageSize,
    totalPages
  }
}

/**
 * 模拟搜索过滤
 */
function filterData<T extends Record<string, any>>(data: T[], filters: Record<string, any>): T[] {
  return data.filter(item => {
    return Object.entries(filters).every(([key, value]) => {
      if (value === undefined || value === null || value === '') return true
      
      // 特殊处理关键字搜索
      if (key === 'keyword') {
        const keyword = value.toLowerCase()
        // 根据数据类型进行不同的搜索策略
        if (item.name || item.companyName) {
          // 客户数据：搜索姓名、公司名称、联系方式
          return (
            (item.name && item.name.toLowerCase().includes(keyword)) ||
            (item.companyName && item.companyName.toLowerCase().includes(keyword)) ||
            (item.phone && item.phone.includes(keyword)) ||
            (item.email && item.email.toLowerCase().includes(keyword))
          )
        } else if (item.username || (item.name && item.role)) {
          // 用户数据：搜索用户名、姓名、邮箱、电话
          return (
            (item.username && String(item.username).toLowerCase().includes(keyword)) ||
            (item.name && String(item.name).toLowerCase().includes(keyword)) ||
            (item.email && String(item.email).toLowerCase().includes(keyword)) ||
            (item.phone && String(item.phone).includes(keyword))
          )
        } else if (item.orderNo) {
          // 订单数据：搜索订单号、客户名称
          return (
            (item.orderNo && item.orderNo.toLowerCase().includes(keyword)) ||
            (item.customerName && item.customerName.toLowerCase().includes(keyword))
          )
        } else if (item.productCode || item.productName) {
          // 产品数据：搜索产品代码、产品名称、类别
          return (
            (item.productCode && item.productCode.toLowerCase().includes(keyword)) ||
            (item.productName && item.productName.toLowerCase().includes(keyword)) ||
            (item.name && item.name.toLowerCase().includes(keyword)) ||
            (item.category && item.category.toLowerCase().includes(keyword))
          )
        }
        return false
      }
      
      // 处理日期范围过滤
      if (key === 'startDate' || key === 'endDate') {
        const itemDate = new Date(item.createTime || item.orderDate || item.date)
        const filterDate = new Date(value)
        
        if (key === 'startDate') {
          return itemDate >= filterDate
        } else {
          return itemDate <= filterDate
        }
      }
      
      // 常规字段过滤
      const itemValue = item[key]
      if (typeof value === 'string') {
        return String(itemValue).toLowerCase().includes(value.toLowerCase())
      }
      
      return itemValue === value
    })
  })
}

/**
 * 模拟排序
 */
function sortData<T extends Record<string, any>>(data: T[], sortBy?: string, sortOrder: 'asc' | 'desc' = 'asc'): T[] {
  if (!sortBy) return data
  
  return [...data].sort((a, b) => {
    const aValue = a[sortBy]
    const bValue = b[sortBy]
    
    if (aValue < bValue) return sortOrder === 'asc' ? -1 : 1
    if (aValue > bValue) return sortOrder === 'asc' ? 1 : -1
    return 0
  })
}

/**
 * 模拟API响应包装器
 */
function createApiResponse<T>(data: T, message: string = '操作成功'): ApiResponse<T> {
  return {
    code: 200,
    message,
    data,
    success: true,
    timestamp: Date.now()
  }
}

/**
 * 模拟API错误响应
 */
function createErrorResponse(message: string, code: number = 400): ApiResponse<null> {
  return {
    code,
    message,
    data: null,
    success: false,
    timestamp: Date.now()
  }
}

/**
 * 通用模拟API方法
 */
export const mockApi = {
  /**
   * 获取列表数据
   */
  async getList<T>(
    resource: string,
    params: {
      page?: number
      pageSize?: number
      sortBy?: string
      sortOrder?: 'asc' | 'desc'
      [key: string]: any
    } = {}
  ): Promise<ApiResponse<{ items: T[]; total: number; page: number; pageSize: number; totalPages: number }>> {
    await delay()
    
    try {
      // 处理特殊的分析路由
      if (resource === 'sales-trend') {
        const data = await mockStore.getData('sales-trend')
        return createApiResponse(data, '获取销售趋势数据成功')
      }
      
      if (resource === 'product-sales') {
        const data = await mockStore.getData('product-sales')
        return createApiResponse(data, '获取产品销售数据成功')
      }
      
      if (resource === 'overview') {
        const data = await mockStore.getData('overview')
        return createApiResponse(data, '获取概览数据成功')
      }
      
      let data = await mockStore.getData(resource)
      
      // 应用过滤
      const { page = 1, pageSize = 10, sortBy, sortOrder = 'asc', ...filters } = params
      data = filterData(data, filters)
      
      // 应用排序
      if (sortBy) {
        data = sortData(data, sortBy, sortOrder)
      }
      
      // 应用分页
      const paginatedResult = paginateData(data, page, pageSize)
      
      return createApiResponse(paginatedResult, '获取列表数据成功')
    } catch (error) {
      console.error('获取列表数据失败:', error)
      return createErrorResponse('获取列表数据失败', 500)
    }
  },

  /**
   * 获取单个数据
   */
  async getById<T>(resource: string, id: string): Promise<ApiResponse<T | null>> {
    await delay()
    
    try {
      const data = await mockStore.getDataById(resource, id)
      if (!data) {
        return createErrorResponse('数据不存在', 404)
      }
      return createApiResponse(data, '获取数据成功')
    } catch (error) {
      console.error('获取数据失败:', error)
      return createErrorResponse('获取数据失败', 500)
    }
  },

  /**
   * 创建数据
   */
  async create<T>(resource: string, data: Partial<T>): Promise<ApiResponse<T>> {
    await delay()
    
    try {
      const newItem = await mockStore.addData(resource, data)
      return createApiResponse(newItem, '创建成功')
    } catch (error) {
      console.error('创建数据失败:', error)
      return createErrorResponse('创建失败', 500)
    }
  },

  /**
   * 更新数据
   */
  async update<T>(resource: string, id: string, data: Partial<T>): Promise<ApiResponse<T | null>> {
    await delay()
    
    try {
      const updatedItem = await mockStore.updateData(resource, id, data)
      if (!updatedItem) {
        return createErrorResponse('数据不存在', 404)
      }
      return createApiResponse(updatedItem, '更新成功')
    } catch (error) {
      console.error('更新数据失败:', error)
      return createErrorResponse('更新失败', 500)
    }
  },

  /**
   * 删除数据
   */
  async delete(resource: string, id: string): Promise<ApiResponse<boolean>> {
    await delay()
    
    try {
      const success = await mockStore.deleteData(resource, id)
      if (!success) {
        return createErrorResponse('数据不存在', 404)
      }
      return createApiResponse(true, '删除成功')
    } catch (error) {
      console.error('删除数据失败:', error)
      return createErrorResponse('删除失败', 500)
    }
  },

  /**
   * 批量删除数据
   */
  async batchDelete(resource: string, ids: string[]): Promise<ApiResponse<{ deletedCount: number }>> {
    await delay()
    
    try {
      const deletedCount = await mockStore.batchDeleteData(resource, ids)
      return createApiResponse({ deletedCount }, `成功删除 ${deletedCount} 条数据`)
    } catch (error) {
      console.error('批量删除失败:', error)
      return createErrorResponse('批量删除失败', 500)
    }
  }
}

export default mockApi